<template>
  <BasicModal
    v-bind="$attrs"
    title="比较浏览"
    @register="register"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :destroyOnClose="true"
    :width="800"
  >
    <Row :gutter="12">
      <Col :span="12">
        <CollapseContainer title="比较图档" :canExpan="false">
          <BasicForm @register="registerCompareForm" />
        </CollapseContainer>
      </Col>
      <Col :span="12">
        <CollapseContainer title="被比较图档" :canExpan="false">
          <template #action>
            <a-button type="primary" @click="selectDocument">选择</a-button>
          </template>
          <BasicForm @register="registerComparedForm" />
        </CollapseContainer>
      </Col>
    </Row>
    <!-- 图档弹窗 -->
    <BasicModal
      v-bind="$attrs"
      title="选择文档"
      @register="registerModal"
      @ok="SubmitDoc"
      @cancel="CancelDoc"
      :destroyOnClose="true"
      :minHeight="450"
      :width="1200"
    >
      <Row :gutter="24">
        <Col :xs="24" :sm="24" :md="24" :lg="4" :xl="4">
          <div style="overflow-y: scroll; overflow-x: hidden; height: 400px">
            <BasicTree :treeData="dataSource" :search="true" @select="selectDir" />
          </div>
        </Col>
        <Col
          :xs="1"
          :sm="1"
          :md="1"
          :lg="1"
          :xl="1"
          style="display: flex; justify-content: center"
        />
        <Col :xs="24" :sm="24" :md="24" :lg="19" :xl="19">
          <BasicTable @register="registerTable" :searchInfo="searchInfo">
            <!-- 创建时间 -->
            <template #creattime="{ text: creattime }">
              <span>
                {{ proxy.$filters.filterTime(creattime) }}
              </span>
            </template>
            <!-- 创建时间 -->
            <template #state="{ text: state }">
              <span>
                {{ proxy.$filters.filterDocumentStatus(state) }}
              </span>
            </template>
            <!-- 是否为关联文件 -->
            <template #isshortcut="{ text: isshortcut }">
              <span>
                {{ proxy.$filters.filterIsRelated(isshortcut) }}
              </span>
            </template>
            <!-- 是否所属零件 -->
            <template #isPartAttachment="{ text: isPartAttachment }">
              <span>
                {{ isPartAttachment === '1' ? t('common.yes') : t('common.no') }}
              </span>
            </template>
            <!-- 零件信息 -->
            <template #partInfo="{ text: partInfo }">
              <span>
                <Tooltip :title="partInfoTitle(partInfo)">
                  {{
                    partInfo != null
                      ? `零件代号：${partInfo.partThitObjectId}-零件名称：${
                          partInfo.partName
                        }-零件类型：${
                          partInfo.partType
                        }-零件状态：${proxy.$filters.filterPartStatus(
                          partInfo.partStatus,
                        )}-零件版本：${partInfo.partVersion}`
                      : '无'
                  }}
                </Tooltip>
              </span>
            </template>
          </BasicTable>
        </Col>
      </Row>
    </BasicModal>
  </BasicModal>
</template>

<script setup lang="ts">
  import { ref, getCurrentInstance } from 'vue';
  import { Row, Col, Tooltip } from 'ant-design-vue';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { CollapseContainer } from '/@/components/Container';
  import { BasicForm, useForm } from '/@/components/Form';
  import { CompareForm, ComparedForm } from './tableData';
  import { Base64 } from 'js-base64';

  // 引入选择图档弹窗
  import { getDocumentColumns, getDocumentConfig } from '../tableData';
  import {
    getDirectoryLevel,
    getPrdFileList,
    ExtractManyFileByAutoView,
  } from '/@/api/demo/document';
  import { BasicTree } from '/@/components/Tree/index';

  const { proxy }: any = getCurrentInstance();
  const dataSource = ref<any[]>([]);
  const getDirParam = ref<number>(0);
  const currentRecord = ref<any>({});
  const searchInfo = ref<any>({
    CurrentDirId: 0,
  });

  // 计算零件信息
  const partInfoTitle = (partInfo) => {
    if (!partInfo) {
      return '暂无零件信息';
    }
    const { partThitObjectId, partName, partType, partStatus, partVersion } = partInfo;
    // 假设你在全局过滤器里定义了 filterDocumentStatus
    const filterState = proxy.$filters.filterPartStatus(partStatus);
    // 多行显示，每行一个字段
    return [
      `零件代号：${partThitObjectId}`,
      `零件名称：${partName}`,
      `零件类型：${partType}`,
      `零件状态：${filterState}`,
      `零件版本：${partVersion}`,
    ].join('\n');
  };

  const selectDocument = () => {
    openSelectDocModal(true);
  };

  // 确定
  const handleSubmit = () => {
    let arr: any = [];
    let paramsA = {
      oid: getCompareFieldsValue().oId,
      ver: getCompareFieldsValue().version,
      type: 0,
    };
    let paramsB = {
      oid: getComparedFieldsValue().oId,
      ver: getComparedFieldsValue().version,
      type: 0,
    };
    arr.push(paramsA);
    arr.push(paramsB);
    ExtractManyFileByAutoView(arr).then((res) => {
      // doctype为3D图纸，则打开3D预览，否则打开2D预览
      if (res[0].doctype != '3D图纸') {
        let file1 = res[0].viewUrl; //文件1
        let file2 = res[1].viewUrl; //文件2
        window.open(
          res[0].serverUrl +
            ':5098/AutoVue/OpenApplet.html?compare2D=true&file1=' +
            encodeURIComponent(Base64.encode(file1)) +
            '&file2=' +
            encodeURIComponent(Base64.encode(file2)),
        );
      } else {
        let file1 = res[0].viewUrl; //文件1
        let file2 = res[1].viewUrl; //文件2
        window.open(
          res[0].serverUrl +
            ':5098/AutoVue/OpenApplet.html?compare3D=true&file1=' +
            encodeURIComponent(Base64.encode(file1)) +
            '&file2=' +
            encodeURIComponent(Base64.encode(file2)),
        );
      }
    });
    handleCancel();
  };
  // 取消
  const handleCancel = () => {
    closeCamPareModal();
  };

  // 提交
  async function SubmitDoc() {
    try {
      setModalPropsModal({ confirmLoading: true });
      setComparedFieldsValue(getSelectRows()[0]);
      CancelDoc();
    } finally {
      setModalPropsModal({ confirmLoading: false });
      CancelDoc();
    }
  }

  // 取消
  const CancelDoc = () => {
    closeDocModal();
  };

  // 选择目录
  const selectDir = (selectedKeys) => {
    searchInfo.value.CurrentDirId = Number(selectedKeys[0]);
    reload();
  };
  // 初始化弹窗
  const [register, { setModalProps: setCamPareModal, closeModal: closeCamPareModal }] =
    useModalInner((data) => {
      setCamPareModal({ confirmLoading: false });
      // 赋值比较内容数据
      setCompareFieldsValue(data.record);
      getDirectoryLevel(getDirParam.value).then((res) => {
        dataSource.value = res;
      });
    });

  // 初始化弹窗
  const [
    registerModal,
    { setModalProps: setModalPropsModal, closeModal: closeDocModal, openModal: openSelectDocModal },
  ] = useModal();

  // 比较内容
  const [
    registerCompareForm,
    { setFieldsValue: setCompareFieldsValue, getFieldsValue: getCompareFieldsValue },
  ] = useForm({
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
    schemas: CompareForm(),
    showResetButton: false,
    showSubmitButton: false,
  });
  // 被比较内容
  const [
    registerComparedForm,
    { setFieldsValue: setComparedFieldsValue, getFieldsValue: getComparedFieldsValue },
  ] = useForm({
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
    schemas: ComparedForm(),
    showResetButton: false,
    showSubmitButton: false,
  });

  // 表格初始化
  const [registerTable, { reload, getSelectRows }] = useTable({
    columns: getDocumentColumns(),
    api: getPrdFileList,
    rowSelection: {
      type: 'radio',
      onSelect: (record) => {
        currentRecord.value = record;
      },
    },
    customRow: (record) => {
      return {
        onClick: () => {
          currentRecord.value = record;
        },
      };
    },
    bordered: true,
    formConfig: getDocumentConfig(), // 表单配置
    useSearchForm: true,
    showIndexColumn: false,
    showTableSetting: true, // 显示表格设置工具
    tableSetting: { fullScreen: true }, // 表格设置工具配置
    pagination: { pageSize: 5, pageSizeOptions: ['5', '10', '15', '20'], defaultPageSize: 5 },
    canResize: false,
    striped: false,
  });
</script>

<style scoped></style>
